package artid.com.arttogoa;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.MySellInfo_Adapter;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Bimp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.GoodsnumParser;
import artid.com.arttogoa.parser.MySellInfoParser;
import artid.com.arttogoa.parser.ReturnOneStateParser;
import artid.com.arttogoa.photo.ImagePagerActivity;
import artid.com.arttogoa.util.MyListView_Util;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称 ：MySellInfo_Activity 类描述 ：我出售的详情页面 创建人 ：耿卫斌
 * 创建时间：2016-7-21 上午10:04:41
 * 
 */
public class MySellInfo_Activity extends BaseActivity implements OnClickListener {
	private Context mContext;
	private int whichActivity = 0;// 默认出售中(0:出售中 1：已下架 )
	private String goods_id;// 商品ID
	private MySellInfoParser mMySellInfoParser;
	private ReturnOneStateParser mReturnOneStateParser;
	private TextView title, price, isguarantee, commendNum, goodsClick,goodsType, goodsSize, goodsAge, certificateNumber, certificateType,introduce;
	private MyListView_Util mListView;
	private MySellInfo_Adapter adapter;
	public PopupWindow window;
	private ScrollView mScrollview;
	private int goods_position;// 商品列表的下标（主要用于删除）
	private Boolean isEditGoods=false;//是否编辑了商品(默认没有)

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mysellinfo);
		setContent(this, getIntent());
		mContext = MySellInfo_Activity.this;
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 当编辑之后可以刷新数据
		if(isEditGoods==true){
			//恢复编辑状态
			isEditGoods=false;
			getData(goods_id);
		}
	}

	private void initView() {
		whichActivity = getIntent().getIntExtra("whichActivity", 0);
		goods_id = getIntent().getStringExtra("goods_id");
		goods_position = getIntent().getIntExtra("goods_position", -1);
		if (whichActivity == 0) {
			mTittle.setText("出售中详情");
		} else {
			mTittle.setText("已下架详情");
		}
		setBack();
		ImageView titlie_right = (ImageView) findViewById(R.id.release_icon);
		titlie_right.setOnClickListener(this);
		titlie_right.setVisibility(View.VISIBLE);
		titlie_right.setImageResource(R.drawable.jzsx_btn_more_nor);
		mMySellInfoParser = new MySellInfoParser();
		mReturnOneStateParser = new ReturnOneStateParser();
		mScrollview = (ScrollView) findViewById(R.id.mysellinfo_scrollview);
		title = (TextView) findViewById(R.id.mysellinfo_title);
		price = (TextView) findViewById(R.id.mysellinfo_price);
		isguarantee = (TextView) findViewById(R.id.mysellinfo_isguarantee);
		isguarantee = (TextView) findViewById(R.id.mysellinfo_isguarantee);
		mListView = (MyListView_Util) findViewById(R.id.mysellinfo_listView);
		mListView.setOnItemClickListener(onItemClick);
		commendNum = (TextView) findViewById(R.id.mysellinfo_commendNum);
		goodsClick = (TextView) findViewById(R.id.mysellinfo_goodsClick);
		goodsType = (TextView) findViewById(R.id.mysellinfo_goodsType);
		goodsSize = (TextView) findViewById(R.id.mysellinfo_goodsSize);
		goodsAge = (TextView) findViewById(R.id.mysellinfo_goodsAge);
		certificateNumber = (TextView) findViewById(R.id.mysellinfo_certificateNumber);
		certificateType = (TextView) findViewById(R.id.mysellinfo_certificateType);
		introduce = (TextView) findViewById(R.id.mysellinfo_introduce);
		//解决Scrollview 嵌套listview 不置顶问题
		mListView.setFocusable(false);
		mScrollview.smoothScrollTo(0, 20);
		getData(goods_id);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.release_icon:
			// 标题右按钮
			if (!StringUtils.isEmpty(goods_id)) {
				showPopwindow(mContext, v, goods_id);
			} else {
				showToast("网络慢，请稍后重试");
			}
			break;

		default:
			break;
		}
	}

	OnItemClickListener onItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < mMySellInfoParser.getGoods_image().size(); i++) {
				list.add(mMySellInfoParser.getGoods_image().get(i).getGoods_image());
			}
			Intent intent = new Intent(mContext, ImagePagerActivity.class);
			// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
			intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS,(Serializable) list);
			intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
			intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_TYPE,ImagePagerActivity.LATTICE);
			startActivity(intent);
		}
	};

	/**
	 * 获取数据
	 */
	private void getData(String good_ID) {
		VolleyBasic.getInstance(this).post(Cache.goodsDetail,
				VolleyMap.getInstance().goodsDetail(good_ID),
				MySellInfoParser.class, new VolleyCallback() {

			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				mMySellInfoParser = (MySellInfoParser) vd.getData();
				title.setText(mMySellInfoParser.getRealname() + "《"+ mMySellInfoParser.getGoods_name() + "》");
				price.setText("￥" + mMySellInfoParser.getGoods_price());
				if ("1".equals(mMySellInfoParser.getIs_auth())) {
					isguarantee.setVisibility(View.VISIBLE);
				} else if ("0".equals(mMySellInfoParser.getIs_auth())) {
					isguarantee.setVisibility(View.GONE);
				}
				commendNum.setText(mMySellInfoParser.getGoods_commend_num());
				goodsClick.setText(mMySellInfoParser.getGoods_click());
				goodsType.setText("种类："+ mMySellInfoParser.getGc_name());
				goodsSize.setText("尺寸："+ mMySellInfoParser.getSpec_value() + " cm");
				goodsAge.setText("年代："+ mMySellInfoParser.getGoods_age());
				if(!StringUtils.isEmpty(mMySellInfoParser.getCode()) && !"null".equals(mMySellInfoParser.getCode())){
					certificateNumber.setText("证书编号："+ mMySellInfoParser.getCode());
				}else{
					certificateNumber.setText("证书编号：无");
				}
				if ("1".equals(mMySellInfoParser.getBy_state())) {
					certificateType.setText("备案证书：电子");
				} else if ("2".equals(mMySellInfoParser.getBy_state())) {
					certificateType.setText("备案证书：纸质");
				} else {
					certificateType.setText("备案证书：无");
				}
				introduce.setText(mMySellInfoParser.getDetail());
				adapter = new MySellInfo_Adapter(mContext,mMySellInfoParser.getGoods_image());
				mListView.setAdapter(adapter);
			}

			public void onError(VolleyError volleyError) {

			}
		});
	}

	/**
	 * 商品数量(在编辑商品的时候要先查看是否有库存) Is_auth : 是否有担保
	 */
	private void getGoodsnum(String good_ID, String Is_auth) {
		VolleyBasic.getInstance(this).post(Cache.goodsnum,
				VolleyMap.getInstance().goodsnum(good_ID),
				GoodsnumParser.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				GoodsnumParser mGoodsnumParser = (GoodsnumParser) vd.getData();
				if (!StringUtils.isEmpty(mGoodsnumParser.getNum())&& !"0".equals(mGoodsnumParser.getNum())) {
					Class editActivity = null;
					if ("0".equals(mMySellInfoParser.getIs_auth())) {
						// 无担保
						editActivity = EditTakePhotosSell_Activity.class;
					} else if ("1".equals(mMySellInfoParser.getIs_auth())) {
						// 有担保
						editActivity = EditFilingQuickSell_Activity.class;
					}
					ArtWorkApp.getInstance().addActivity(MySellInfo_Activity.this);
					Intent i = new Intent(mContext, editActivity);
					i.putExtra("goodsType", Bimp.GOODS_EDIT);
					i.putExtra("MySellInfoParser",(Serializable) mMySellInfoParser);
					//标识编辑商品之后用来刷新订单的
					isEditGoods=true;
					startActivity(i);
				}else{
					showToast("该商品暂时不能编辑");
				}
			}
			public void onError(VolleyError volleyError) {

			}
		});
	}

	/**
	 * 商品上/下架/删除(我出售的列表使用相同) 1删除 ，2下架，3上架
	 */
	private void goodsControl(String good_ID, final String type) {
		VolleyBasic.getInstance(this).post(Cache.otherGoods,
				VolleyMap.getInstance().otherGoods(good_ID, type),
				ReturnOneStateParser.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				mReturnOneStateParser = (ReturnOneStateParser) vd.getData();
				int retrunActivity = whichActivity;
				if ("1".equals(mReturnOneStateParser.getState())) {
					if ("1".equals(type)) {
						// 删除成功
						retrunActivity = whichActivity;
						// 通知刷新列表（删除相对应的商品）
						Intent intent = new Intent("com.MySell_fragment.receiver");
						intent.putExtra("intentActivity", "我出售的详情"+ whichActivity + "-删除");
						intent.putExtra("goods_position",goods_position);
						mContext.sendBroadcast(intent);
						finish();
					} else if ("2".equals(type)) {
						// 下架成功返回已下架列表
						retrunActivity = 1;
					} else if ("3".equals(type)) {
						// 上架成功返回出售中列表
						retrunActivity = 0;
					}
					// 通知刷新列表（展示不同的列表(上下架)）
					Intent intent = new Intent("com.MySell_Activity.receiver");
					intent.putExtra("intentActivity", "我出售的详情-上下架");
					intent.putExtra("retrunActivity", retrunActivity);
					mContext.sendBroadcast(intent);
					finish();
				} else if ("0".equals(mReturnOneStateParser.getState())) {
					// 失败
					showToast("操作失败");
				}
			}

			public void onError(VolleyError volleyError) {

			}
		});
	}

	public void showPopwindow(final Context mContext, View v, final String id) {
		// 利用layoutInflater获得View
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popupwindow_mysellinfo, null);
		// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
		final PopupWindow window = new PopupWindow(view,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		// 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
		window.setFocusable(true);
		// 必须要给调用这个方法，否则点击popWindow以外部分，popWindow不会消失
		window.setBackgroundDrawable(new BitmapDrawable());
		// 在参照的View控件下方显示
		window.showAsDropDown(
				MySellInfo_Activity.this.findViewById(R.id.release_icon),-NetUtils.dip2px(mContext, 70),NetUtils.dip2px(mContext, 5));
		// 这里检验popWindow里的button是否可以点击
		TextView editBtn = (TextView) view
				.findViewById(R.id.popupwindow_mysellinfo_edit);
		editBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 编辑（先判断是否有库存）
				getGoodsnum(goods_id, mMySellInfoParser.getIs_auth());
				window.dismiss();
			}
		});
		TextView goodsControlBtn = (TextView) view.findViewById(R.id.popupwindow_mysellinfo_goodsControl);
		if (whichActivity == 0) {
			// 下架
			goodsControlBtn.setText("下架");
		} else if (whichActivity == 1) {
			// 上架
			goodsControlBtn.setText("上架");
		}

		goodsControlBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (whichActivity == 0) {
					// 下架
					goodsControl(goods_id, "2");
				} else if (whichActivity == 1) {
					// 上架
					goodsControl(goods_id, "3");
				}

				window.dismiss();
			}
		});
		TextView deleteBtn = (TextView) view.findViewById(R.id.popupwindow_mysellinfo_delete);
		deleteBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 删除
				goodsControl(goods_id, "1");
				window.dismiss();
			}
		});
		// popWindow消失监听方法
		window.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				System.out.println("popWindow消失");
			}
		});
	}
}
